<template>
  <div class="ter-new-home-page">
    <el-form :inline="true" :model="searchObj" class="demo-form-inline" ref="topbar">
      <el-form-item label="终端分组">
        <el-select @change="getList" v-model="searchObj.groupId" placeholder="请选择分组">
          <el-option
            v-for="(item, index) in [{group_name: '全部', id: ''}, ...groupList]"
            :label="item.group_name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="全局场景">
        <el-select @change="sendSceneCmd" v-model="searchObj.sceneId" placeholder="请选择场景">
          <el-option
            v-for="item in [...globalScenList]"
            :key="item.id"
            :label="item.title"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="终端排序">
        <el-select @change="changeClientSort" v-model="searchObj.type" placeholder="请选择排序">
          <el-option
            v-for="item in [{label: '全部', value: ''}, {label: '终端列表', value: 1},{label: '终端名称', value: 2},{label: '终端ip', value: 3}]"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <div class="float-right-button">
        <el-button @click="goBackHome" icon="el-icon-back" class="back-btn btn-font">内容管理</el-button>
        <el-button v-if="!isCanSelect" icon="el-icon-more" @click="showCheckboxSelect" type="primary" class="btn-font">选择</el-button>
        <el-button v-if="isCanSelect" icon="el-icon-close" @click="showCheckboxSelect" class="back-btn btn-font">取消</el-button>
        <el-button v-if="isCanSelect" icon="el-icon-check" @click="selectAllCheckBox" type="primary" class="btn-font">全选</el-button>
<!--        <el-button v-if="isCanSelect" icon="el-icon-document" @click="showSendFile" type="primary" class="btn-font">内容</el-button>-->
      </div>
    </el-form>
    <div class="ter-list-row" ref="middleContent" :style="{'margin-top': middleContentTop + 'px'}">
      <el-checkbox-group v-model="checkList">
        <el-col
          :span="6"
            v-for="(item, index) in terList"
            :key="index"
        >
          <div
            :class="['ter-list-col','ter-list-col-'+index, checkList.includes(item.id) ? 'selected':'']"
          >
            <div  @click="goToDetail(item)" class="ter-detail-row"></div>
            <div class="video-bg">
<!--              <HlsVideo-->
<!--                :hls-url="`http://${item.ip}:8888`"-->
<!--                :container="`ter-list-col-${index}`"-->
<!--              ></HlsVideo>-->
<!--              <live-player :video-url="`http://${item.ip}:8889/stream/V4`" live='true'></live-player>-->
<!--              <live-player :video-url="`ws://${item.ip}:8080/stream/V4.live.flv`" live='true'></live-player>-->
              <iframe :src="`http://${item.ip}:8889/stream/V4`" class="vendor-view__iframe"></iframe>
            </div>

            <el-checkbox v-show="isCanSelect" :label="item.id"></el-checkbox>
            <!-- <div class="float-right-switch">
              <div v-if="item.status == '1'" class="el-icon-video-play"></div>
              <div v-else-if="item.status == '0'" class="el-icon-video-pause"></div>
            </div> -->
            <!--        <div-->
            <!--          @click.capture.stop.prevent="delTerMethods(item)"-->
            <!--          class="el-icon-error del-button"-->
            <!--        ></div>-->
            <div class="float-right-words">
              <div>{{item.ip}}</div>
            </div>

            <div class="float-bottom-name">
              <div>{{item.name}}</div>
            </div>

            <div class="float-left-words">
              <div>{{item.resolution_rate}}</div>
            </div>
          </div>
        </el-col>
      </el-checkbox-group>
    </div>
    <!-- <el-pagination
      class="page-nation"
      :current-page="searchObj.page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="searchObj.pageSize"
      layout="total, prev, pager, next"
      :total="total"
      @current-change="handleCurrentChange"
    /> -->
    <el-pagination
      class="page-nation"
      :current-page="searchObj.page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="searchObj.pageSize"
      layout="total, prev, pager, next, jumper"
      :total="total"
      @current-change="handleCurrentChange"
      ref="bottombar"
    />

    <WarnPanelDialog
      :statusProp="statusProp"
      @confirmHandler="confirmDelMethods"
      @cancelHandler="cancelHandler"
    ></WarnPanelDialog>

    <el-dialog
      title="选择内容"
      :visible.sync="isShowUploadDialog"
      width="60%"
      :before-close="handleClose"
      class="dialog">
      <div>
        <div>
          <el-form :inline="true" :model="searchMedia" class="demo-form-inline" style="padding: 0 ">
            <el-form-item label="素材类型">
              <el-select clearable @change="changeMediaType" v-model="searchMedia.type" placeholder="请选择">
                <el-option
                  v-for="item in mediaTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <CommonTable
            class="newHomecommonTable"
            ref="quickOperateContentRef"
            :is-selection="true"
            row-key="id"
            :is-show-index="false"
            :is-has-opera="false"
            :t-column-data="quickOperateSelectContentCol"
            :remote-api="getFileList"
            :query-params="searchFileParams"
            :is-reserve-select="true"
            @changeRow="changeFileRowMethods"
            operating-width="180px"
          >
            <template slot="media_name" slot-scope="scope">
              <div class="file-name-row">
                <img :src="scope.row.media_link" class="file-icon" alt="">
                <div>{{scope.row.media_name}}</div>
              </div>
            </template>
          </CommonTable>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirmSaveStep">确定</el-button>
      </span>
    </el-dialog>

    <!--文件分发选择终端-->
    <TerListDialog
      :show-ter-dialog="showTerDialog"
      ref="terListDialogRef"
      @on-cancel="cancelTerDialog"
      @on-confirm="confirmSelectTer"
    ></TerListDialog>
  </div>
</template>

<script>
import HlsVideo from "@/views/terminalDetail/components/hlsVideo1.vue";
import * as sceneService from '@/views/scene/service'
import * as service from './service'
import EventBus from "@/utils/eventBus";
import {suffixFileMapStr} from "@/utils/config";

import {quickOperateSelectContentCol} from '../distribute/tableCol/quickOperateSelectContentCol'
import * as fileService from '@/views/distribute/service'
import {sendCmd} from "@/views/terminalDetail/utils/sendCmd";
export default {
  components: {
    HlsVideo
  },
  data() {
    return {
      middleContentTop: 0,
      searchFileParams: {
        name: '',
        fileType: 2
      },
      isCanClick: false,
      searchMedia: {
        type: ''
      },
      getFileList: fileService.getFileList,
      globalScenList: [],
      quickOperateSelectContentCol,
      isCanSelect: false,
      terForm: {
        name: '',
        groupId: ''
      },
      allFiles: [],
      showTerDialog: false,
      statusProp: false,
      total: 0,
      mutiDelList: [],
      clickCache: {},
      mediaTypeOptions: [],
      searchObj: {
        sceneId: '',
        type: 3,
        page: 1,
        pageSize: 8
      },
      selectMedia: [],
      terList: [],
      terTotalList: [],
      checkList: [],
      isShowUploadDialog: false,
      groupList: [],
      searchSecneObj: {
        page: 1,
        type: 1,
        pageSize: 20000000
      }
    }
  },
  async mounted() {
    this.getAllClient()
    this.getAllFile()
    this.getGroupList()
    this.getSceneList()
    this.getClientSort()
    this.mediaTypeOptions = []
    Object.keys(suffixFileMapStr).forEach((item) => {
      const tmp = {
        value: item,
        label: suffixFileMapStr[item]
      }
      this.mediaTypeOptions.push(tmp)
    })
    this.getList();
    window.addEventListener('resize', () => {
      this.resize()
    })
  },
  methods: {
    confirmSelectTer() {
      this.showTerDialog = false
    },
    cancelTerDialog() {
      this.showTerDialog = false
    },
    getAllFile() {
      const params = {
        page: 1,
        pageSize: 2000000
      }

      fileService.getFileList(params).then((res) => {
        this.allFiles = res.data.records.slice()
      })
    },
    clicMethods(ev) {
      ev.preventDefault();
    },
    changeCheckbox(ev) {
      console.log('ev ---', ev)
    },
    getSceneList() {
      const params = Object.assign({}, this.searchSecneObj)
      sceneService.getWindowScene(params).then((res) => {
        this.globalScenList = res.data.records.slice()
      })
    },
    getGroupList() {
      service.getGroupList({page: 1,pageSize: 200000000}).then((res) => {
        this.groupList = [...res.data.records]

        this.getList()
      })
    },
    changeFileRowMethods(rows) {
      this.selectMedia = [...rows]
    },
    getMediaList() {
      this.$refs.quickOperateContentRef.queryData({...this.searchFileParams}, (res) => {
        const mediaIdList = this.clickCache.media_id && this.clickCache.media_id.indexOf(',')?this.clickCache.media_id.split(','): [this.clickCache.media_id]
        const checkRows = []
        mediaIdList.forEach((item) => {
          const findIndex = res.findIndex((result) => {
            return item == result.id
          })

          if(findIndex !== -1) {
            checkRows.push(res[findIndex])
          }
        })
        if(mediaIdList.length > 0) {
          this.$refs.quickOperateContentRef.toggleRowSelectionMethods(checkRows)
        }

        console.log('this.$refs.quickOperateContentRef ---', this.$refs.quickOperateContentRef)
      })
    },
    changeMediaType(val) {
      this.searchFileParams.mediaType = val
      this.getMediaList()
    },
    confirmSaveStep() {
      console.log('checkList ---', this.selectMedia)
      if(this.selectMedia.length === 0) {
        this.$message.error('请选择分发的内容')
        return
      }
      let clientIds = [...this.checkList]
      let mediaIds = []
      this.selectMedia.forEach((item) => {
        mediaIds.push(item.id)
      })
      const params = {
        clientIds,
        mediaIds
      }
      fileService.quicklySend(params).then(() => {
        this.$message.success('发送成功')
        this.isShowUploadDialog = false
        this.showTerDialog = true
        this.$nextTick(() => {
          this.$refs.terListDialogRef.getFileRateList()
        })
      })
    },
    showSendFile() {
      if(this.checkList.length === 0) {
        this.$message.error('请选择分发的终端')
        return
      }
      this.isShowUploadDialog = true
      this.$nextTick(() => {
        this.getMediaList()
      })
    },
    selectAllCheckBox() {
      if(this.checkList.length === this.terList.length) {
        this.checkList = []
      } else {
        this.checkList = []
        this.terList.forEach((item) => {
          this.checkList.push(item.id)
        })
      }
    },
    handlerSceneWindows (window,client, callback=() =>{}) {
      // 关闭所有分屏
      console.log('关闭所有分屏', window)
      sendCmd('window', 'closeAll', client, () => {
        this.startSceneHandlerWindow(window, client, () => {})
      })
    },
    startSceneHandlerWindow(window, client, callback=() => {}) {
      // 开窗
      // console.log('window ---', window)
      window.forEach((item, key) => {
        let i = key
        const findFileIndex = this.allFiles.findIndex((result) => {
          // console.log('result ---', result)
          return result.id == item.media_id
        })
        // console.log('this.allFiles[findFileIndex] ---', this.allFiles[findFileIndex])
        item.media_name = this.allFiles[findFileIndex].media_name
        item.media_type = this.allFiles[findFileIndex].media_type
        item.location = this.allFiles[findFileIndex].location
        setTimeout(() => {
          sendCmd('globalScene', 'open', {row:item, i, content:item , subMode:'', client})
        }, i * 300)
      })
    },
    sendSceneCmd() {
      this.$confirm('是否发送全局终端指令?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 场景id查场景详情
        const paramsDetail = {
          sceneId: this.searchObj.sceneId
        }
        sceneService.getWindowSceneDetail(paramsDetail).then((result) => {
          result.data.clients.forEach((item, key) => {
            const findTerIndex = this.terTotalList.findIndex((result) => {
              return result.id == item.client_id
            })
            const clientDetail = this.terTotalList[findTerIndex]

            let window = item.layout.windows
            this.handlerSceneWindows(window, clientDetail, () => {

            })
          })
          this.$message.success('执行成功')
        })
      }).catch(() => {

      });
    },
    goBackHome() {
      this.$router.push('/distribute/video')
    },
    showCheckboxSelect() {
      this.isCanClick = !this.isCanClick
      this.isCanSelect = !this.isCanSelect
      this.checkList = []
    },
    confirmUploadFile() {
      if(this.clickCache.status == 0) {
        this.$message.error('修改失败,终端已离线')
        return
      }
      if(!this.clickCache.ip) {
        console.warn('没有找到对应的终端ip ---', this.clickCache)
      }
      const params = {
        ...this.terForm,
        mac: this.clickCache.mac,
        ip: this.clickCache.ip
      }

      service.clientEdit(params).then(() => {
        this.$message.success('修改成功')
        this.getList()
        this.handleClose()
      })
    },
    updateItemName(row) {
      this.clickCache = {...row}
      Object.keys(this.terForm).forEach((fields) => {
        this.terForm[fields] = row[fields]
      })

      this.terForm.groupId = row.group_id
      this.terForm.id = row.id
      this.showTerDialog = true
    },
    getClientSort() {
      service.getClientSort({}).then((res) => {
        // this.searchObj.type = res.data
        this.searchObj.type = 3
      })
    },
    changeClientSort() {
      this.getList(() => {
        const params = {
          type: this.searchObj.type
        }

        service.updateClientSort(params).then(() => {

        })
      })
    },
    getList(callback=() => {}) {
      let _this = this;
      service.getClientList(this.searchObj).then(res => {
        this.total = res.data.total
        this.terList = [...res.data.records]
        this.$nextTick(() => {
          _this.resize();
        })
        callback()
      })
    },
    resize() {
      let domList = document.querySelectorAll('.ter-list-col')
      for(let i = 0;i < domList.length;i++) {
        const width = domList[i].getBoundingClientRect().width
        const height = width * (9 / 16)
        domList[i].style.height = `${height}px`
        // console.log('height ---', height)
      }
      var k = 1200;
      let rem = (document.documentElement.clientHeight - 42) / k * 100;
      let topbarHeight = rem;
      let middleContentHeight = this.$refs.middleContent.clientHeight;
      let bottombarHeight = rem * 0.9;
      let middleHeight = middleContentHeight * (this.terList.length < 5 ? 2 : 1);
      let top = window.innerHeight- topbarHeight - middleHeight  - bottombarHeight;
      this.middleContentTop = top / 2;

    },
    getAllClient() {
      service.getClientList({page: 1, pageSize: 20000}).then(res => {
        this.terTotalList = [...res.data.records]
      })
    },
    handleClose() {
      this.isShowUploadDialog = false
      this.showTerDialog = false
      this.addTerModal = false
    },
    cancelHandler() {
      this.statusProp = false
      this.clickCache = {}
      this.mutiDelList = []
    },
    confirmDelMethods() {
      if(this.mutiDelList.length > 0) {
        const params = {
          ids: []
        }
        this.mutiDelList.forEach((item) => {
          params.ids.push(item.id)
        })

        service.clientMutiDelete(params.ids).then(() => {
          this.$message.success('删除成功')
          this.getList()
          this.statusProp = false
          this.mutiDelList = []
          this.$refs.terminalTableRef.clearSelectionMethods()
        })
      } else {
        const params = {
          id: this.clickCache.id
        }
        service.clientDelete(params).then(() => {
          this.$message.success('删除成功')
          this.getList()
          this.statusProp = false
          this.clickCache = {}
        })
      }
    },
    delTerMethods(row) {
      this.clickCache = Object.assign({}, row)
      this.statusProp = true
    },
    goToDetail(row) {
      if(this.isCanClick) {
        const findIndex = this.checkList.findIndex((item) => {
          return item == row.id
        })
        if(findIndex === -1) {
          this.checkList.push(row.id)
        } else {
          this.checkList.splice(findIndex, 1)
        }
        return
      }
      window.localStorage.setItem('clientDetail', JSON.stringify(row))
      this.$router.push({ path: '/terminal/terminalDetail', query: { id: row.id }})
    },
    handleCurrentChange(page) {
      this.searchObj.page = page
      this.getList()
    }
  }
}
</script>

<style scoped lang="scss">
  .ter-new-home-page{
    width: 100%;
    height: 100%;
    background: linear-gradient( 180deg, #021132 0%, #072C62 100%);
    position: relative;

    .dialog {
      ::v-deep .el-dialog{
      margin-top: 1rem !important;
      }

      ::v-deep .el-dialog__header{
        background-color: #072C62;
        height: 1.1rem;
        line-height: .8rem;
      }
      ::v-deep .el-dialog__title{
        color: #fff;
        font-size: .26rem;
      }
      ::v-deep .el-dialog__headerbtn{
        top: .3rem;
        right: .3rem;
        font-size: .26rem;
      }
      ::v-deep .el-dialog__body{
        background: linear-gradient( 180deg, #072C62 0%, #01143D 100%);
      }
      ::v-deep .el-dialog__footer{
        background-color: #01143D;
        border: none;
        height: 1rem;
        padding: .2rem .4rem .4rem;
      }
      ::v-deep .el-button--default, ::v-deep .el-button--primary{
        padding: 0.15rem 0.15rem !important;
        font-size: .23rem;
      }
      ::v-deep .el-table {
        border: none;
        max-height: 9rem !important;
      }
      ::v-deep .el-table__body-wrapper {
        border: none;
        max-height: 7rem !important;
      }
      ::v-deep .el-table th.el-table__cell{
        background-color: #00407B !important;
        border: none;
        color: #fff;
        font-size: .23rem;
      }
      ::v-deep .el-table th.el-table__cell>.cell,
      ::v-deep .el-table td.el-table__cell>.cell{
        line-height: .32rem;
        border: none;
      }
      ::v-deep .el-table .el-table__body td{
        border: none;
        color: #fff;
        font-size: .22rem;
        line-height: .23rem;
      }
      ::v-deep .el-table__body tr.current-row>td.el-table__cell {
        background-color: #00407B;
      }
      ::v-deep .el-table--enable-row-hover .el-table__body tr:hover>td.el-table__cell {
        background-color: #00407B;
      }
      ::v-deep .el-table .el-table__body tr.el-table__row:nth-child(odd) {
        background-color: #072C62;
      }
      ::v-deep .el-table .el-table__body tr.el-table__row:nth-child(even) {
        background-color: #082E65;
      }
      ::v-deep .el-checkbox__inner{
        width: .25rem;
        height: .25rem;
      }
    }

    .ter-list-row{
      flex-wrap: wrap;
      .el-checkbox-group{
        width: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;
        position: relative;
        padding: 0 .1rem;

        .selected {
          outline: .08rem solid #409EFF;
        }
        .ter-list-col {
          margin: .6rem .15rem;
          position: relative;
          flex-shrink: 0;
          background-color: #ccc;
          color: white;
          cursor: pointer;
          border-radius: .1rem;

          .ter-detail-row{
            width: 100%;
            height: 100%;
            //background: #000;
            position: absolute;
            top: 0;
            left: 0;
            border-radius: .2rem;
            z-index: 100;
            background: transparent;
          }
          .video-bg{
            width: 100%;
            height: 100%;
            //background: #000;
            position: absolute;
            top: 0;
            left: 0;
            border-radius: .2rem;
          }

          .el-checkbox{
            position: absolute;
            right: .2rem;
            top: .2rem;
            z-index: 2000;

            .el-checkbox__label{
              display: none!important;
            }
            // ::v-deep .el-checkbox__inner{
            //   width: .3rem;
            //   height: .3rem;
            // }
            // ::v-deep .el-checkbox__inner:after{
            //   left: .1rem;
            //   top: .05rem;
            // }
          }

          .float-right-words{
            padding: .1rem;
            border-radius: .15rem;
            background: rgba(3,18,51,0.5);
            position: absolute;
            right: .2rem;
            bottom: .2rem;
            font-size: .2rem;
          }

          .float-bottom-name{
            position: absolute;
            bottom: -.5rem;
            left: 0;
            width: 100%;
            text-align: center;
            color: #fff;
            font-size: .25rem;
          }

          .float-left-words{
            padding: .1rem;
            border-radius: .15rem;
            background: rgba(3,18,51,0.5);
            position: absolute;
            left: .2rem;
            top: .2rem;
            font-size: .2rem;
          }
        }
      }

      .ter-list-add-col{
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .page-nation{
      position: absolute;
      bottom: 0;
      width: 100%;
      text-align: center;
      padding: .15rem 0;
      background-color: #021234;
      height: .9rem;

      ::v-deep .el-pagination__total,::v-deep .el-pagination__jump{
        color: #fff;
        font-size: .25rem;
      }
      ::v-deep .el-pager li{
        color: #fff;
        background-color: rgba(0,0,0,0);
        font-size: .25rem;
        margin-left: .2rem;
        margin-right: .2rem;
        position: relative;
        top: -3px;
      }
      ::v-deep .btn-next {
        color: #fff;
        background-color: rgba(0,0,0,0);
        margin-left: .2rem;
      }
      ::v-deep .btn-prev {
        color: #fff;
        background-color: rgba(0,0,0,0);
        font-size: .25rem;
      }
      ::v-deep .el-pagination__editor.el-input .el-input__inner{
        color: #fff;
        background-color: #0C3889;
        border: none;
        outline: none;
        font-size: .25rem;
      }
    }
  }

  .commonTable{
    ::v-deep .el-table::before{
        background: none !important;
    }
    ::v-deep .el-table--border::after {
      width: 0px;
    }

    ::v-deep .el-table__header-wrapper {
      background: none;
    }
    ::v-deep .el-pagination__total,::v-deep .el-pagination__jump{
      color: #fff;
      font-size: .25rem;
    }
    ::v-deep .el-pager li{
      color: #fff;
      background-color: rgba(0,0,0,0);
      font-size: .25rem;
      margin-left: .2rem;
      margin-right: .2rem;
    }
    ::v-deep .btn-next {
      color: #fff;
      background-color: rgba(0,0,0,0);
      margin-left: .2rem;
    }
    ::v-deep .btn-prev {
      color: #fff;
      background-color: rgba(0,0,0,0);
      font-size: .25rem;
    }
    ::v-deep .el-pagination__editor.el-input .el-input__inner{
      color: #fff;
      background-color: #0C3889;
      border: none;
      outline: none;
      font-size: .25rem;
    }
    ::v-deep .el-input__inner{
      background-color: #0C3889;
      border: none;
      outline: none;
      color: #ffffff;
      font-size: .25rem;
    }

    ::v-deep .el-input--suffix{
      width: 1.8rem;
    }
  }

  .demo-form-inline{
    padding: .15rem .25rem;
    position: relative;
    height: 1rem;

    ::v-deep .el-form-item__label{
      color: rgba(255,255,255,0.7);
      font-size: .22rem;
      font-weight: 400;
      line-height: .6rem;
    }
    ::v-deep .el-form-item__content {
      vertical-align: middle;
    }
    ::v-deep .el-input__inner{
      background-color: #0C3889;
      color: #fff;
      border: none;
      outline: none;
      height: .6rem;
      font-size: .22rem;
      font-weight: 400;
    }
  }

  .float-right-switch{
    position: absolute;
    left: 5px;
    top: 5px;

    .el-icon-video-pause{
      font-size: 26px;
      color: #F56C6C;
    }
    .el-icon-video-play{
      font-size: 26px;
      color: #67C23A;
    }
  }

  .float-right-button{
    position: absolute;
    right: .25rem;
    top: .2rem;

    .btn-font {
      font-size: .22rem;
      height: 0.6rem;
      padding: 0 .2rem !important;
    }

    .back-btn{
      background-color: #223568;
      border: 1px solid #3A6897;
      color: #FFFFFF;
    }
  }
</style>

<style>
.ter-list-col {
  .el-checkbox{

    .el-checkbox__label{
      display: none!important;
    }
  }
}
</style>
